package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

public class AdminCheckFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		String url = request.getServletPath();
		String contextPath = request.getContextPath();
		
		if (url.equals("")) {
			url += "/";
		}
		User user = (User) request.getSession().getAttribute("loginUser");
		if (url.startsWith("/Admin_")) {
			
			if(user==null||!user.getIsAdm()){
				response.sendRedirect(contextPath + "/Login.jsp");
				return;	
			}else if(user!=null&&user.getIsAdm()) {
				chain.doFilter(req, resp);
				return;
			}
		}
		// if ((url.startsWith("/") && !url.startsWith("/Login"))) {// 若访问后台资源
		// //||url.startsWith("/User_register")
		// if (url.endsWith("Login.jsp")||url.endsWith("User_register.jsp")) {
		// chain.doFilter(req, resp);
		// return;
		// }
		// // 过滤到login
		// User user = (User) request.getSession().getAttribute("loginUser");
		// if (user == null) {// 转入管理员登陆页面
		// response.sendRedirect(contextPath + "/Login.jsp");
		// return;
		// }
		// }
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
